/* eslint-disable no-unused-vars */
const mock = require('./mock')
const sync = require('./mock/sync')
const webpack = require('webpack')
const AddAssetHtmlPlugin = require('add-asset-html-webpack-plugin')
const TerserPlugin = require('terser-webpack-plugin')
const path = require('path')
const bodyParser = require('body-parser')

const DEVELOPMENT_URL = 'http://127.0.0.1:8000'

const utils = require('./config/utils')

// 多页配置
// const pages = utils.pages()
// 单页入口
const pages = {
  index: {
    entry: 'src/main.js',
    template: 'template/map.html',
    filename: 'index.html',
    chunks: ['chunk-vendors', 'chunk-common', 'index']
  }
}

// 代理
const proxyConfig = {
  '/python': {
    target: DEVELOPMENT_URL,
    changeOrigin: true,
    pathRewrite: {
      '^/python': '/python'
    }
  },
}

// vue-cli配置文件
module.exports = {
  outputDir: 'dist',
  configureWebpack: config => {
    return {
      module: {
        rules: [
          {
            test: /\.(cur)(\?.*)?$/,
            loader: 'url-loader',
            options: {
              limit: 10000,
              name: utils.assetsPath('imgs/[name].[hash:7].[ext]')
            }
          }
        ]
      },
      resolve: {
        alias: {
        }
      },
      plugins: [
        new webpack.DllReferencePlugin({
          context: path.join(__dirname),
          manifest: require('./build/dll/vendor-manifest.json')
        }),
        new AddAssetHtmlPlugin({
          filepath: path.resolve(__dirname, './build/dll/*.dll.js'),
          // 文件输出目录
          outputPath: 'vendor',
          // 脚本或链接标记的公共路径
          publicPath: 'vendor'
        }),
        new webpack.DefinePlugin({
          'process.env.SAAS': JSON.stringify(process.env.SAAS)
        })
      ],
      optimization: {
        minimizer: [
          new TerserPlugin({
            terserOptions: {
              ecma: undefined,
              warnings: false,
              parse: {},
              compress: {
                drop_console: true,
                drop_debugger: false,
                pure_funcs: ['console.log'] // 移除console
              }
            }
          })
        ]
      }
      // externals: {
      //   'AMapUI': 'AMapUI'
      // }
    }
  },
  chainWebpack: config => {
    // TODO: Remove this workaround once https://github.com/vuejs/vue-cli/issues/2463 is fixed
    // Remove preload plugins for multi-page build to prevent infinite recursion
    // FIXED: 打包时多页应用存在模块相互引用时报错
    Object.keys(pages).forEach(page => {
      config.plugins.delete(`preload-${page}`)
      config.plugins.delete(`prefetch-${page}`)
    })
    // 修复HMR
    config.resolve.symlinks(true)
    config.plugin('define')
      .tap(args => {
        args[0]['process.env'].SAAS = JSON.stringify(process.env.SAAS)
        return args
      })
  },
  lintOnSave: true,
  publicPath: process.env.NODE_ENV === 'development'
    ? '/'
    : './',
  productionSourceMap: false, // 生产环境不输出sourcemap
  devServer: {
    before(app, server) {
      app.use(bodyParser.urlencoded({ extended: false }))
      app.use(bodyParser.json())
    },
    // 代理配置
    proxy: (() => {
      // 将同步时需要监听的proxy事件注入到http-proxy中
      Object.values(proxyConfig).forEach(config => {
        config = Object.assign(config, sync)
      })
      return proxyConfig
    })()
  },
  css: {
    loaderOptions: {
      postcss: {
        plugins: [
          require('postcss-px-to-viewport')({
            unitToConvert: 'px',
            viewportWidth: 1920,
            unitPrecision: 5,
            propList: [
              '*'
            ],
            viewportUnit: 'vw',
            fontViewportUnit: 'vw',
            selectorBlackList: [],
            minPixelValue: 0,
            mediaQuery: false,
            replace: true,
            exclude: /(\/|\\)(node_modules)(\/|\\)/
          })

        ]
      }
    }
  },
  // 多页配置
  pages: pages,
  // 以下是pwa配置
  pwa: {
    iconPaths: {
      favicon32: '',
      favicon16: '',
      appleTouchIcon: '',
      maskIcon: '',
      msTileImage: ''
    }
  }
}
